// pages/message/index.js
Page({
  data: {
    loading: false,  // 加载状态
    noMore: false,   // 是否无更多数据
    lastDoc: null,    // 最后一条文档（用于分页）
    app:null,
    db:null,
    userInfo:{},
    isLoggedIn:false,
    showDialog:false,
    showMessage:'',
    showTip:'',
    messageList: [],
    unreadCount: 0, // 未读消息数
  },

  onShow() {
    const app = getApp();
    this.setData({
      app:app
    })
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db
    })
    const userInfo = wx.getStorageSync('userInfo');
    console.log('business userInfo',userInfo)
    this.setData({
      isLoggedIn: !!userInfo,
      userInfo: userInfo || {},
      loading: false,  // 加载状态
      noMore: false,   // 是否无更多数据
      lastDoc: null,    // 最后一条文档（用于分页）
      showDialog:false,
      showMessage:'',
      showTip:'',
      messageList: [],
      unreadCount: 0, // 未读消息数
    });

    this.getMessageList(true)
  },
  getMessageList(init = false){
    if (this.data.loading || this.data.noMore) return
    
    this.setData({ loading: true })
    wx.showLoading({ title: '加载中...' })
    const _ = this.data.db.command // 获取数据库命令构造器
    this.data.db.collection('newsList')
    .orderBy('createTime','desc')
    .skip(init ? 0 : this.data.messageList.length) // 跳过已加载数据
    .limit(20) // 每次20条
    .where(
      _.and([
        _.or([
          { receiverId: this.data.userInfo._openid }, // 条件1: a 字段等于 openid
          // { _openid: this.data.userInfo._openid }  // 条件2: b 字段等于 openid
        ]),
        // { isRead: false } // 条件3: isRead 必须为 false
      ])
    ).get()
    .then(res => {
      if(res && res.data && res.data.length > 0){
        this.setData({
          messageList: init ? res.data.map(item => ({
            ...item,
            formattedTime: this.getFormats(item.createTime)
          })) : [...this.data.messageList, ...res.data.map(item => ({
            ...item,
            formattedTime: this.getFormats(item.createTime)
          }))], 
          noMore: res.data.length < 20,
        lastDoc: res.data[res.data.length - 1] // 记录最后一条
        })
      }
      this.calculateUnreadCount();
    })
    .catch (err =>  {
      wx.showToast({ title: '加载失败', icon: 'none' })
    })
    .finally(() => {
      this.setData({ loading: false })
      wx.hideLoading()
    }) 
  },
   // 滚动到底部触发
  onScrollToLower() {
    this.getMessageList()
  },
  // 计算未读消息数
  calculateUnreadCount() {
    const unreadCount = this.data.messageList.filter(item => !item.isRead).length;
    this.setData({ unreadCount });
    if(unreadCount > 0){
      wx.setTabBarBadge({
        index: 3,
        text: unreadCount + ''
      });
    }else{
      wx.removeTabBarBadge({
        index: 3,
      });
    }

  },
  // 全部已读
  markAllAsRead() {
    const _ = this.data.db.command
    const arr = this.data.messageList
    .filter(message => !message.isRead)
    .map(message => message._id);
    
    this.data.db.collection("newsList").where(
      _.and([
        _.or([
          { receiverId: this.data.userInfo._openid }, // 条件1: a 字段等于 openid
          // { _openid: this.data.userInfo._openid }  // 条件2: b 字段等于 openid
        ]),
        { isRead: false }, // 条件3: isRead 必须为 false
        {_id: _.in(arr)}
      ])
    )
    .update({
      data: {
        isRead: true, // 将所有未读消息标记为已读
        readTime: this.data.db.serverDate() // 服务器时间
      }
    });

    const updatedList = this.data.messageList.map(item => ({
      ...item,
      isRead: true,
    }));
    this.setData({ messageList: updatedList, unreadCount: 0 });
    wx.showToast({ title: "全部已读", icon: "success" });
    this.calculateUnreadCount();
  },
  delete(e){
    wx.showLoading({
      title: `删除中...`,
    })
    const id = e.currentTarget.dataset.id
    this.data.db.collection('newsList').doc(id).remove({
      success: res => {
        const arr = this.data.messageList.filter(item => item._id !== id)
        console.log('this.data.messageList',this.data.messageList,arr)
        this.setData({
          messageList:arr
        })
        this.calculateUnreadCount();
        wx.hideLoading()
        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    })
  },
  // 全部删除
  deleteAllMessages() {
    wx.showModal({
      title: "提示",
      content: "确定删除所有消息吗？",
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: `删除中...`,
          })
          const _ = this.data.db.command
          const arr = this.data.messageList.map(item => item._id)
          // 批量删除符合条件的所有文档
          this.data.db.collection('newsList').where(      
            _.and([
              _.or([
                { receiverId: this.data.userInfo._openid }, // 条件1: a 字段等于 openid
                // { _openid: this.data.userInfo._openid }  // 条件2: b 字段等于 openid
              ]),
              {_id: _.in(arr)}
            ])
          ).remove({
            success: res => {
              this.setData({ messageList: [], unreadCount: 0 });
              this.calculateUnreadCount();
              wx.hideLoading()
              wx.showToast({ title: "全部删除", icon: "success" });
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({ title: "删除失败", icon: "error" });
            }
          })
        }
      },
    });
  },
  showUnRead(e){
    const id = e.currentTarget.dataset.id;
    const tip = e.currentTarget.dataset.tip;
    const message = e.currentTarget.dataset.message;
    const receiverId = e.currentTarget.dataset.receiverid;
    const arr = this.data.messageList
    console.log('receiverId',this.data.userInfo._openid,receiverId)
    this.data.db.collection("newsList")
    .doc(id)
    .update({
      data: {
        isRead: true, // 将所有未读消息标记为已读
        readTime: this.data.db.serverDate() // 服务器时间
      }
    })
    .then(res => {
      arr.forEach(item => {
        if(item._id === id){
          item.isRead = true
        }
      })
      this.setData({
        messageList:arr,
        showDialog:true,
        showTip:tip,
        showMessage:message
      })
      this.calculateUnreadCount();
    })
  },
  confirmDialog(){
    this.setData({
      showDialog:false
    })
  },
  getFormats(timestamp) {
    const date = new Date(timestamp);
  
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
});